using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using ExcelDataReader;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;

namespace Dream.SecondLevel
{
    //sky 24-11-24 05:34:11 
    public class ExcelReader : MonoBehaviour
    {
        public static void LoadExcelData(string address, Action<List<ExcelData>> onComplete)
        {
            Addressables.LoadAssetAsync<TextAsset>(address).Completed += handle =>
            {
                if (handle.Status == AsyncOperationStatus.Succeeded)
                {
                    var textAsset = handle.Result;
                    var excelDataList = ParseExcelData(textAsset.text);
                    onComplete(excelDataList);
                }
                else
                {
                    Debug.LogError("Failed to load Excel data.");
                }
            };
        }

        private static List<ExcelData> ParseExcelData(string csvData)
        {
            var dataList = new List<ExcelData>();
            using (var reader = new StringReader(csvData))
            {
                string line;
                var isFirstLine = true;

                while ((line = reader.ReadLine()) != null)
                {
                    if (isFirstLine)
                    {
                        isFirstLine = false;
                        continue; // Skip header line
                    }

                    var values = line.Split(new[] { ',' }, StringSplitOptions.None);
                    var data = new ExcelData
                    {
                        speaker = values[0],
                        content = values[1],
                        backGroundImageFileName = values[2],
                        characterSpriteFileName = values[3],
                        choiceOfEnd = values[4],
                        firstChoiceFile = values[5],
                        secondChoiceFile = values[6],
                        characterAction = values[7].Trim('"'),
                        executor = values[8]
                    };
                    dataList.Add(data);
                }
            }

            return dataList;
        }


        public static List<ExcelData> ReadExcel(string filePath)
        {
            var excelData = new List<ExcelData>();
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            using (var stream = File.Open(filePath, FileMode.Open, FileAccess.Read))
            {
                using (var reader = ExcelReaderFactory.CreateReader(stream))
                {
                    do
                    {
                        while (reader.Read())
                        {
                            var data = new ExcelData();
                            data.speaker = reader.IsDBNull(0) ? string.Empty : reader.GetString(0);
                            data.content = reader.IsDBNull(1) ? string.Empty : reader.GetString(1);
                            data.backGroundImageFileName = reader.IsDBNull(2) ? string.Empty : reader.GetString(2);
                            data.characterSpriteFileName = reader.IsDBNull(3) ? string.Empty : reader.GetString(3);
                            data.choiceOfEnd = reader.IsDBNull(4) ? string.Empty : reader.GetString(4);
                            data.firstChoiceFile = reader.IsDBNull(5) ? string.Empty : reader.GetString(5);
                            data.secondChoiceFile = reader.IsDBNull(6) ? string.Empty : reader.GetString(6);
                            data.characterAction = reader.IsDBNull(7) ? string.Empty : reader.GetString(7);
                            data.executor = reader.IsDBNull(8) ? string.Empty : reader.GetString(8);
                            excelData.Add(data);
                        }
                    } while (reader.NextResult());
                }
            }

            return excelData;
        }

        public struct ExcelData
        {
            public string speaker; //当前说话人的名字
            public string content; //说话内容
            public string backGroundImageFileName; //背景文件名称，看这条对话完成后是否切换场景，有就切换（选项一）
            public string characterSpriteFileName; //角色立绘（选项二）
            public string choiceOfEnd; //故事行为
            public string firstChoiceFile; //选项一跳转的文件
            public string secondChoiceFile; //选项而跳转的文件
            public string characterAction; //角色行为
            public string executor;
        }
    }
}